package com.lxq.springBoot.jedis;

import java.math.BigDecimal;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.stereotype.Component;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class JedisClient {
	
	private JedisPool pool;
	
	/**
	 * 初始化JedisPool
	 */
	public  JedisClient(){
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(10);
		config.setMinIdle(2);
		pool = new JedisPool(config, "localhost", 6379);
		
	}
	
	/**
	 * 获取jedis
	 * @return
	 */
	public  Jedis getJedis(){
		Jedis jedis = pool.getResource();
		return jedis;
	}
	
	/**
	 * 关闭jedis
	 * @param jedis
	 */
	public  void closeJedis(Jedis jedis){
		jedis.close();
	}
	
	/**
	 * 延长过期时间
	 * @param jedis
	 * @param key
	 * @param expireTime
	 */
	public  void extendExpire(String key,int expireTime){
		Jedis jedis = getJedis();
		jedis.expire(key, expireTime);
	}
	
	public String get(String key){
		String result = "";
		Jedis jedis = null;
		try {
			 jedis = getJedis();
			 result = jedis.get(key);
		} finally {
			closeJedis(jedis);
		}
		return result;
	}
	
	public String set(String key,String value){
		Jedis jedis = null;
		
		try {
			jedis = getJedis();
			return jedis.set(key, value);
		} finally {
			closeJedis(jedis);
		}
		 
	}
	
	private RuntimeSchema<Book> schema = RuntimeSchema.createFrom(Book.class);
	
	@Test
	public void testJedis(){
		Jedis jedis = new Jedis("localhost", 6379);
		jedis.set("java_test_jedis_123", "java_test_jedis");
		jedis.select(1);
		jedis.set("123", "123");
		jedis.setex("key_key", 10, "value_value");
		jedis.close();
	}
	
	@Test
	public void testJedisPool(){
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(10);
		config.setMinIdle(2);
		JedisPool pool = new JedisPool(config, "localhost", 6379);
		Jedis jedis = pool.getResource();
		String result = jedis.get("java_test_jedis_123");
		Assert.assertEquals(result, "java_test_jedis");
		pool.close();
	}
	
	@Test
	public void testSetJedisWithProroStuff(){
		Jedis jedis = new Jedis("localhost", 6379);
		Book book = new Book("java", new BigDecimal(100));
		byte[] BookByte = ProtobufIOUtil.toByteArray(book, schema, LinkedBuffer.allocate( LinkedBuffer.DEFAULT_BUFFER_SIZE));
		jedis.set(new String("potostuff").getBytes(), BookByte);
		jedis.close();
	}
	
	@Test
	public void testGetJedisWithProroStuff(){
		Jedis jedis = new Jedis("localhost", 6379);
		byte[] bookByte = jedis.get(new String("protostuff").getBytes());
		if (bookByte != null) {
			Book book = schema.newMessage();
			ProtobufIOUtil.mergeFrom(bookByte, book, schema);
			System.out.println(book);
		}
		jedis.close();
	}
}
